package multimanipulators.converters;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import be.djdb.db.Statics;
import be.djdb.manipulators.streams.util.externstuf.Base64Coder;
import be.djdb.utils.AResourceFile;

import multimanipulators.interfaces.Converters;

public class Converter_ImageIncluder implements Converters {
	private static final boolean DEBUG = false;
	@Override
	/* (non-Javadoc)
	 * 		replace(java.lang.String, java.io.OutputStreamWriter)
	 * 		OutputStreamWriter outW = new OutputStreamWriter(System.out);
	 * 		try {
	 * 			new StreampieceIMGincluder().replace("img location in jar",outW);
	 * 		} catch (IOException e) {
	 * 			e.printStackTrace();
	 * 		}
	 */
	public void manipulate(char[] toreplace, OutputStreamWriter out){
		appendimg(new String(toreplace), out);
	}
	/**
	 * @param in
	 * @param Doutstream
	 * @throws IOException
	 */
	private void appendimg(String imgname, OutputStreamWriter out) {
			try {
				out.append("data:image/gif;base64,");
				encodeStream(new BufferedInputStream(new AResourceFile().takeajarfilestream(imgname)),out);//new String(buffer)
				//encodeStream(new BufferedInputStream(new AResourceFile().takealocaltestfilestream(imgname)),Doutstream);
			} catch (IOException e){
				if (DEBUG){log(Level.ALL,"ERROR:FILENOTFOUND:Converter_ImageIncluder: " + imgname+">>>>>>>>>>>");}   
			}
	}
	public void encodeStream(InputStream in,OutputStreamWriter Doutstream ) throws IOException {
		   int lineLength = 72;
		   byte[] buf = new byte[lineLength/4*3];
		   while (true){
			   int len = in.read(buf);
			   if (len <= 0) break;
			   Doutstream.write (Base64Coder.encode(buf,len));
		   }
	}
    /**
     * @param level
     * @param msg
     */
    private static  void log(Level level, String msg ){
        String tag ="<>>>>*"+Statics.LIBNAME+"-"+Statics.COPYRIGHTBY+"*<<<<>";
        Logger.getLogger(Converter_ImageIncluder.class.getName()).log(level, tag + msg);
    }
	@Override
	public String getname() {
		return Converter_ImageIncluder.class.getName();
	}
}

